//
//  ConShoppingMallsController.m
//  Shengzhuli
//
//  Created by FXGuo on 17/3/19.
//  Copyright © 2017年 kamangkeji. All rights reserved.
//

#import "ConShoppingMallsController.h"
#import "ShoppingMallsCell.h"
#import "LLSegmentedControl.h"
#import "ConGoodsDetailController.h"
#import "SingleNetService.h"
#import "MBProgressHUD+MJ.h"
#import <MJRefresh.h>
#import "BusinessNetwork.h"
#import "GoodsTypeModel.h"
#import "SZLAccountHelper.h"
#import "MenuScreeningView.h"
#import "UIImage+Extension.h"
#import "HomeNetService.h"
#import "SZLSearchViewController.h"
#import <Masonry.h>
#import "CoverView.h"
#import "BuyCarsViewController.h"
#import "SZLMessageListViewController.h"
#import "LLSegmentedControl.h"

@interface ConShoppingMallsController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,MenuScreeningViewDelegate>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *sources;
@property (nonatomic,strong) NSArray *types;//商品分类
@property (nonatomic,assign) NSInteger curPage;
@property (nonatomic,weak) UISearchBar *searchBar;
@property (nonatomic,weak) MenuScreeningView *menuScreeningView;
@property (nonatomic,strong) LLSegmentedControl *segmentedControl;
@property (nonatomic,strong) HomeGoodsTypeModel *selectType;//选择的type
/*menuScreeningView分类 **/
@property (nonatomic,assign) NSInteger oneTypeId;
@property (nonatomic,assign) NSInteger twoTypeId;
@property (nonatomic,assign) NSInteger threeTypeId;

@property (nonatomic,assign) float historyY;

@end

@implementation ConShoppingMallsController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.curPage = 1;
    [self setNavi];
//    [self setUpView];
    [self getGoodsData];
}
- (void)getGoodsData
{
    [self getGoodsType];
    [self getGoodsList];
}
- (void)setNavi
{
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW-80-20, 35)];
    UIColor *color =  self.navigationController.navigationBar.backgroundColor;
    titleView.backgroundColor = color;
    
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, ScreenW-80-20, 35)];
    searchBar.placeholder = @"输入您正在找的宝贝";
    UIImage* searchBarBg = [UIImage getImageWithColor:RGBColorOne(240) andHeight:35.0f];
//    [searchBar setBackgroundImage:searchBarBg];
//    [searchBar setBackgroundColor:[UIColor whiteColor]];
    [searchBar setSearchFieldBackgroundImage:searchBarBg forState:UIControlStateNormal];
    searchBar.delegate = self;
    self.searchBar = searchBar;
    [titleView addSubview:searchBar];
    self.navigationItem.titleView = titleView;
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
//    [rightBtn setBackgroundImage:GetImage(@"add_white") forState:UIControlStateNormal];
//    [rightBtn setTitle:@"＋" forState:UIControlStateNormal];
    [rightBtn setImage:GetImage(@"购物车") forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(buyCarClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = -5;
    
    self.navigationItem.rightBarButtonItems = @[negativeSpacer,[[UIBarButtonItem alloc]initWithCustomView:rightBtn]];
}
- (void)setSegmentController
{
    LLSegmentedControl *segmentedControl = [[LLSegmentedControl alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 40)];
    NSMutableArray *titles = [NSMutableArray array];
    for (HomeGoodsTypeModel *model in self.types) {
        [titles addObject:model.productTypeName];
    }
    segmentedControl.titleArray = titles;
    segmentedControl.backgroundColor = [UIColor whiteColor];
    segmentedControl.segmentedControlLineStyle = LLSegmentedControlStyleUnderline;
    segmentedControl.segmentedControlTitleSpacingStyle = LLSegmentedControlTitleSpacingStyleWidthAutoFit;
    // lineWidthEqualToTextWidth 设置为YES, lineWidth 属性则不需设置
    segmentedControl.lineWidthEqualToTextWidth = YES;
    segmentedControl.textColor = [UIColor blackColor];
    segmentedControl.selectedTextColor = RGBColor(234, 111, 90);
    segmentedControl.lineColor = RGBColor(234, 111, 90);
    segmentedControl.font = [UIFont systemFontOfSize:16];
    segmentedControl.selectedFont = [UIFont boldSystemFontOfSize:18];
    segmentedControl.lineHeight = 2.f;
    if (titles.count<=5) {
//        segmentedControl.titleSpacing = 10;
        segmentedControl.titleWidth = (ScreenW-(titles.count-1)*10)/titles.count;
    }else {
        segmentedControl.titleSpacing = 30;
    }
    segmentedControl.defaultSelectedIndex = 0;
    self.segmentedControl = segmentedControl;
    [self.view addSubview:segmentedControl];
    [self.view addSubview:self.tableView];
    __WEAK
    [segmentedControl segmentedControlSelectedWithBlock:^(LLSegmentedControl *segmentedControl, NSInteger selectedIndex) {
        HomeGoodsTypeModel *model = self.types[selectedIndex];
        self.selectType = model;
        self.curPage = 1;
        [self getGoodsList];
    }];
    [segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view);
        make.height.mas_equalTo(40);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        if (weakSelf.model) {
            make.bottom.mas_equalTo(self.view);
        }else {
            make.bottom.mas_equalTo(self.view).offset(-49);
        }
        make.top.mas_equalTo(self.segmentedControl.mas_bottom);
    }];
}
- (void)buyCarClick
{
    BuyCarsViewController *carVc = [[BuyCarsViewController alloc]init];
    [self.navigationController pushViewController:carVc animated:YES];
}
- (void)rightItemClick
{
    CoverView *cover = [[CoverView alloc]initWithFrame:[UIScreen mainScreen].bounds Titles:@[@"消息",@"购物车"]backStart:47];
    __WEAK
    cover.btnBlock = ^(NSInteger index){
        if ([SZLAccountHelper shouldLogin]) return;
        if (index == 0) {
            SZLMessageListViewController *messageVc = [[SZLMessageListViewController alloc]init];
            [weakSelf.navigationController pushViewController:messageVc animated:YES];
        }else{
            BuyCarsViewController *carVc = [[BuyCarsViewController alloc]init];
            [weakSelf.navigationController pushViewController:carVc animated:YES];
        }
    };
    [cover showSelectView];
}
- (void)setUpView
{
    MenuScreeningView *menuScreeningView = [[MenuScreeningView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 40) firstTypeName:self.model.productTypeName];
    self.menuScreeningView = menuScreeningView;
    menuScreeningView.backgroundColor = [UIColor whiteColor];
    menuScreeningView.showY = 104;
    [self.view addSubview:menuScreeningView];
    menuScreeningView.zeroClick = ^(UIButton *btn) {
        self.oneTypeId = 0;
        self.twoTypeId = 0;
        self.twoTypeId = 0;
        [self getGoodsList];
    };
    menuScreeningView.endEndingBlock = ^{
        [self.searchBar resignFirstResponder];
    };
    if (self.model) {
        self.oneTypeId = self.model.ID;
    }
    menuScreeningView.delegate = self;
    [menuScreeningView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view);
        make.height.mas_equalTo(40);
    }];
    
    [self.view addSubview:self.tableView];
    __WEAK
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        if (weakSelf.model) {
            make.bottom.mas_equalTo(self.view);
        }else {
            make.bottom.mas_equalTo(self.view).offset(-49);
        }
        make.top.mas_equalTo(self.menuScreeningView.mas_bottom);
    }];
}

- (void)setTableViews
{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight+40, ScreenW,ScreenH-SafeAreaTopHeight-SafeAreaBottomHeight-40) style:UITableViewStyleGrouped];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.sectionFooterHeight = 0.01;
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ShoppingMallsCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ShoppingMallsCell class])];
    self.tableView = tableView;
    [self.view addSubview:tableView];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.menuScreeningView.mas_bottom);
    }];
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.curPage = 1;
        [self getGoodsList];
    }];
    tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.curPage++;
        [self getGoodsList];
    }];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}
#pragma mark - Table view data delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sources.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShoppingMallsCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ShoppingMallsCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.sources[indexPath.section];
    cell.buyCarBlock = ^(NormalShopGoodsModel *model) {
        [self addBuyCar:model];
    };
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (![SZLAccountHelper shouldLogin]) {
        ConGoodsDetailController *goodsVc = [[ConGoodsDetailController alloc]init];
        NormalShopGoodsModel *model = self.sources[indexPath.section];
        goodsVc.productNo = model.productNo;
        [self.navigationController pushViewController:goodsVc animated:YES];
    }
}
- (void)menuScreeningViewRequestType:(NSInteger)type ID:(NSInteger)ID
{
    if (type == 1) {
        self.oneTypeId = ID;
    }else if (type == 2){
        self.twoTypeId = ID;
    }else {
        self.threeTypeId = ID;
    }
    [self.sources removeAllObjects];
    [self getGoodsList];
}
- (void)getGoodsList
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"pageNo"] = @(self.curPage);
    if (self.selectType.ID) {
        parame[@"isInIndexActivity"] = @(self.selectType.ID);
    }
    [self showClearBgWaiter];
    [SingleNetService getMailGoodsListsWithParame:parame response:^(BOOL success, NSString *msg, NSArray *gooods) {
        [self hideWaiter];
        [self hideReloadView];
        [self hideNoDataLab];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        self.tableView.mj_footer.hidden = (gooods.count < 20);
        if (success) {
            if (self.curPage == 1) {
                [self.sources removeAllObjects];
                if (gooods.count == 0) {
                    [self showNoDataLab:self.tableView range:CGRectMake(0, self.tableView.height*0.5, ScreenW, 20) title:@"抱歉,没有符合条件的商品"];
                }else{
                    [self hideNoDataView];
                }
            }
            [self.sources addObjectsFromArray:gooods];
            [self.tableView reloadData];
        }else{
            if ([msg isEqualToString:NetworkError]) {
                if (self.sources.count == 0) {
                    [self showReloadViewWithTarget:self action:@selector(getGoodsData)];
                }
            }
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
//加入购物车
- (void)addBuyCar:(NormalShopGoodsModel *)model
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"productNo"] = model.productNo;
    parame[@"count"] = @(1);
    [self showClearBgWaiter];
    [SingleNetService addBuyCarParame:parame response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
        if (success) {
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}

//获取商品类型
- (void)getGoodsType
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"type"] = @"1";
    [self showClearBgWaiter];
    [BusinessNetwork getGoodsTypeWithParame:parame response:^(BOOL success, NSString *msg, NSArray *types) {
        [self hideWaiter];
        if (success) {
            self.types = types;
            [self setSegmentController];
        }else{
            [MBProgressHUD showError:msg];
        }
    }];
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    SZLSearchViewController *searchVc = [[SZLSearchViewController alloc]init];
    searchVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVc animated:YES];
    return NO;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.sectionFooterHeight = 0.01;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ShoppingMallsCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ShoppingMallsCell class])];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.curPage = 1;
            [self getGoodsList];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            self.curPage++;
            [self getGoodsList];
        }];
    }
    return _tableView;
}
- (NSMutableArray *)sources
{
    if (!_sources) {
        _sources = [NSMutableArray array];
    }
    return _sources;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.searchBar resignFirstResponder];
//    if (scrollView.contentOffset.y < self.historyY) {
//        [self.navigationController setNavigationBarHidden:NO animated:YES];
////        self.segmentedControl.showY = SafeAreaTopHeight+40;
//        [self.segmentedControl mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(self.view);
//        }];
//    } else if (scrollView.contentOffset.y > self.historyY) {
//        [self.navigationController setNavigationBarHidden:YES animated:YES];
////        self.segmentedControl.showY = 60;
//        [self.segmentedControl mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(self.view).offset(20);
//        }];
//    }
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.historyY = scrollView.contentOffset.y;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.searchBar resignFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.menuScreeningView menuScreeningViewDismiss];
}

@end
